#!/bin/bash
#
# Simple nginx init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.

### BEGIN INIT INFO
# Provides:     nginx
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    nginx 
# Description:          nginx 
### END INIT INFO

BASE_DIR=/opt/nginx-1.18.0
EXEC=$BASE_DIR/sbin/nginx
CONF=$BASE_DIR/conf/nginx.conf
START_CMD="$EXEC -c $CONF"

get_nginx_pid(){
    NGINX_PID=$(ps gaux | grep "$START_CMD" | grep -v grep | awk '{print $2}')
}

start_nginx(){
    if test -n "$NGINX_PID" 
    then
        echo "nginx is already running."
    else
        echo -n "Starting nginx."
        $START_CMD
        for loop in 1 2 3
        do
            sleep 1
            echo -n "."
        done
        get_nginx_pid
        if test -n "$NGINX_PID" 
        then
            echo "success!"
        else
            echo "failure!"
        fi
    fi
}

reload_nginx(){
    if test -z "$NGINX_PID" 
    then
        echo "nginx is not running."
    else
        echo -n "Reloading nginx."
        $EXEC -s reload
        for loop in 1 2 3
        do
            sleep 1
            echo -n "."
        done
        get_nginx_pid
        if test -n "$NGINX_PID" 
        then
            echo "success!"
        else
            echo "failure!"
        fi
    fi
}

stop_nginx(){
    if test -z "$NGINX_PID" 
    then
        echo "nginx is not running."
    else
        echo -n "Shuting down nginx."
        $EXEC -s stop
        while test -n "$NGINX_PID"
        do
            sleep 1
            get_nginx_pid
            echo -n "." 
        done
        echo "success!"
    fi
}

get_nginx_pid

case "$1" in
    start)
        start_nginx
        ;;
    reload)
        reload_nginx
        ;;
    stop)
        stop_nginx
        ;;
    status)
        if test -n "$NGINX_PID" 
        then
            ps gaux | grep "$START_CMD" | grep -v grep
        else
            echo "inactive"
        fi
        ;;
    *)
        echo "Please use start,reload,status,stop as first argument"
        ;;
esac